﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ZhangLogSysV1d0;

namespace NoDriverPrintHelperV1d0.Service
{
    /// <summary>
    /// 
    /// </summary>
    public class ThreadTcpClientConnectV1d0
    {
        /// <summary>
        ///打印任务开始打印事件
        /// </summary>
        public event EventHandler<TcpClient> ConnectedReadyEvent = null;
        /// <summary>
        /// 是否运行中
        /// </summary>
        private bool runing = false;
        public string PrinterIp = "127.0.0.1";
        public int PrinterPort = 9100;
        private TcpClient _PrinterTcpClient = null;
        public bool IsConnectionSuccessful = false;
        public static object IsDisconnectedLock = new object();

        private bool _IsDisconnected = true;
        public bool IsDisconnected
        {
            get
            {
                lock (IsDisconnectedLock)
                {
                    return _IsDisconnected;
                }
            }
            set
            {
                lock (IsDisconnectedLock)
                {
                    _IsDisconnected = value;
                }
            }
        }
        private ManualResetEvent TimeoutObject = new ManualResetEvent(false);
        public TcpClient PrinterTcpClient
        {
            get
            {
                lock (PrinterTcpClientLock)
                {
                    return _PrinterTcpClient;
                }
            }
            set
            {
                lock (PrinterTcpClientLock)
                {
                    _PrinterTcpClient = value;
                }
            }
        }
        public static object PrinterTcpClientLock = new object();
        /// <summary>
        /// epc扫描线程
        /// </summary>
        private Thread Thread_TcpConnect = null;

        /// <summary>
        /// 线程序号
        /// </summary>
        public int Thread_index = 0;

        /// <summary>
        /// 启动线程
        /// </summary>
        public void StartThread()
        {
            this.Thread_TcpConnect = new Thread(new System.Threading.ThreadStart(this.ThreadStart));
            this.runing = true;
            //作为后台线程
            this.Thread_TcpConnect.IsBackground = false;
            //启动线程
            this.Thread_TcpConnect.Start();
        }
        /// <summary>
        /// 停止线程
        /// </summary>
        public void StopThread()
        {
            this.runing = false;
        }

        /// <summary>
        /// 线程启动
        /// </summary>
        private void ThreadStart()
        {
            while (runing)
            {
                try
                {
                    if(IsDisconnected)
                    {
                        PrinterTcpClient = TryConnect(PrinterIp, PrinterPort, 3000);
                        if (IsConnectionSuccessful)
                        {
                            if (ConnectedReadyEvent != null) ConnectedReadyEvent(this, PrinterTcpClient);
                            IsDisconnected = false;
                        }
                        else IsDisconnected = true;
                    }                    
                }
                catch (Exception ex)
                {
                    //连接超时
                    continue;
                }
            }
        }

        public TcpClient TryConnect(string serverip, int serverport, int timeoutMiliSecond)
        {
            TimeoutObject.Reset();
            TcpClient tcpclient = new TcpClient();
            try
            {
                //设定发数据的超时时间
                tcpclient.SendTimeout = 1000;
                tcpclient.BeginConnect(serverip, serverport, new AsyncCallback(CallBackMethod), tcpclient);
                //等待信号timeoutMiliSecond事件若干秒，
                if (TimeoutObject.WaitOne(timeoutMiliSecond, false))
                {
                    if (IsConnectionSuccessful)
                    {
                        return tcpclient;
                    }
                }
                else
                {
                    //在指定时间内没有等到信号，则关闭tpclient，发出超时异常
                    IsConnectionSuccessful = false;
                    tcpclient.Close();
                    throw new TimeoutException("TimeOut Exception");
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return tcpclient;
        }
        /// <summary>
        /// 异步连接的回调函数
        /// </summary>
        /// <param name="asyncresult"></param>
        private void CallBackMethod(IAsyncResult asyncresult)
        {
            try
            {
                IsConnectionSuccessful = false;
                TcpClient tcpClient = asyncresult.AsyncState as TcpClient;
                if (tcpClient.Client != null)
                {
                    tcpClient.EndConnect(asyncresult);
                    IsConnectionSuccessful = true;
                }
            }
            catch (Exception ex)
            {
                IsConnectionSuccessful = false;
            }
            finally
            {
                //线程继续运行
                TimeoutObject.Set();
            }
        }
    }

}
